package tv.accedo.achi.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import tv.accedo.achi.model.App;

/**
 * A dao class with application model database operations 
 * @author Bo Liang
 *
 */
@Component
public class AppDao {

	private SessionFactory sessionFactory; //injection
	private App app; //injection
	
	/**
	 * Get application object by achievement sn.
	 * <p>obtain the application object instance by using this application serial number<br>
	 * @param app_sn	application serial number
	 * @return			application object
	 */
	public App getAppByAppsn(String app_sn) {
		Session session = null; 
		try {
//			session = SessionFactoryUtil.getSessionFactory().openSession(); 
			session = sessionFactory.openSession();
			Query query = session.createQuery("from App app where app.app_sn = ?")
						  .setParameter(0, app_sn); 
			app = (App)query.uniqueResult();  
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
//			SessionFactoryUtil.closeSession(session);
			session.close();
		}
		return app; 
	}
	
	/**
	 * Get all applications from database.
	 * @return application objects List
	 */
	@SuppressWarnings("unchecked")
	public List<App> getAllApps() {
		List<App> appList = new ArrayList<App>(); 
		Session session = null; 
		try {
//			session = SessionFactoryUtil.getSessionFactory().openSession(); 
			session = sessionFactory.openSession();
			Query query = session.createQuery("from App app"); 
			appList = query.list();  
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
//			SessionFactoryUtil.closeSession(session);
			session.close();
		}
		return appList;
	}
	
	/**
	 * 
	 * @param app_sn
	 * @return
	 */
	public int getAppNumByAppsn(String app_sn) {
		int appNum = 0; 
		Session session = null; 
		try {
			session = sessionFactory.openSession();
			Query query = session.createSQLQuery("select count(app_sn) from t_achi where app_sn = ?")
					      .setParameter(0, app_sn); 
			appNum = ((Number)query.uniqueResult()).intValue(); 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return appNum;
	}
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	public App getApp() {
		return app;
	}
	
	@Resource
	public void setApp(App app) {
		this.app = app;
	}
	
}
